﻿using cnBlogs.ViewModel;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Media;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace cnBlogs.Common.UserControls
{
    public sealed partial class Backgound
    {

        const double SECONDS = 20;
        static DispatcherTimer dispatcherTimer = new DispatcherTimer();
        static Backgound()
        {
            dispatcherTimer.Interval = TimeSpan.FromSeconds(SECONDS);
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Start();
        }

        static Backgound Current;

        public Backgound()
        {
            this.InitializeComponent();
            Current = this;
            if (bitmapimage.UriSource != null)
            {
                background.Background = new ImageBrush { ImageSource = bitmapimage };
                image_dynamicBackGround.Opacity = 0d;
            }

        }

        static void dispatcherTimer_Tick(object sender, object e)
        {
            dispatcherTimer.Interval = dispatcherTimer.Interval.Add(TimeSpan.FromSeconds(SECONDS));
            loadimage();
        }
        static BitmapImage bitmapimage = new BitmapImage();
        private static async void loadimage()
        {
            DynamicBackGoung dg = new DynamicBackGoung();
            await dg.GetResource();
            bitmapimage = new BitmapImage();
            bitmapimage.ImageOpened += bitmapimage_ImageOpened;
            bitmapimage.UriSource = new Uri(dg.Url);
            if (Current != null)
            {
                Current.image_dynamicBackGround.Source = bitmapimage;
            }

            //background.Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri(dg.Url)) };
        }

        static void bitmapimage_ImageOpened(object sender, RoutedEventArgs e)
        {
            FadeInBackGround();
        }

        private static void FadeInBackGround()
        {
            if (Current != null)
            {
                Storyboard sb = Current.Resources["FadeIn"] as Storyboard;
                sb.Completed += sb_Completed;
                sb.Begin();

            }
        }

        static void sb_Completed(object sender, object e)
        {
            Storyboard sb = sender as Storyboard;
            sb.Completed -= sb_Completed;
            Current.background.Background = new ImageBrush { ImageSource = bitmapimage };
            Current.image_dynamicBackGround.Opacity = 0d;
        }
    }
}
